package ch.unisi.inf.pfii.teamwhite.risk.core;

/**
 * 
 * @author Matteo Bellan: bellanm@lu.unisi.ch
 * @author Andrea Michelotti: micheloa@lu.unisi.ch
 * @author Ranganathan Ramasubramanian: ramasubr@lu.unisi.ch
 *
 */

import java.util.Random;

import ch.unisi.inf.pfii.teamwhite.risk.core.player.Player;

//This class menage and control the battles
public final class AttackHandler {

	private Random random;
	
	private String lost;
	private String destroyed;

	public AttackHandler() {
		random = new Random();
	}

//	This method computes the result of an attack, given the attacking and defending ships 
	public final void handleAttack(final Player currentPlayer,
								   final int attackingShips, final int defendingShips,
								   final Planet planet) {
		int attacker = attackingShips;
		int defender = defendingShips;
		final int defensiveShieldRate = 20;
		if (planet.getBuilding().getName().equals("Defensive Shield") || planet.getBuilding().getName().equals("Eldest Council")) {
			defender += (attacker * defensiveShieldRate) / 100;
		}
		while (attacker > 0 && defender > 0) {
			int attackerResult = throwDice(attacker);
			int defenderResult = throwDice(defender);
			attacker -= defenderResult;
			defender -= attackerResult;
			
			destroyed = shipsCheckerAfterAttack(defender, attackerResult);
			lost = shipsCheckerAfterAttack(attacker, defenderResult);
		}
		if (attacker <= 0) {
			if (defender <= 0) {
				planet.resetShips();
				planet.createShip();
			} else {
				planet.resetShips();
				int i = 1;
				while (i <= defender) {
					planet.createShip();
					i++;
				}
			}
		} else if (defender <= 0) {
			if (!planet.getOwner().getName().equals("Gaia")) {
				planet.getOwner().getTerritory().remove(planet);
			}
			if (currentPlayer.getType().equals("Ai")) {
				if (planet.isCapital()) {
					currentPlayer.setMoney(currentPlayer.getMoney() + 3000); 
				}
				currentPlayer.conquerPlanet(planet);
			} else {
				if (planet.isCapital()) {
					currentPlayer.setMoney(currentPlayer.getMoney() + 3000); 
				}
				currentPlayer.conquerPlanet(planet);
			}
			planet.resetShips();
			int i = 1;
			while (i <= attacker) {
				planet.createShip();
				i++;
			}
		}
	}

//	This method simulate the dice roll
	private final int throwDice(final int n) {
		int tmpThrow = random.nextInt(n + 1);
		return tmpThrow;
	}

//	This method checks the number of ships of the defender and the attacker, after the attack
	private final String shipsCheckerAfterAttack(final int numberOfShips, final int randomResult1) {
		String result = "";
		if (randomResult1 > numberOfShips) {
			result = "every";
		} else {
			result = "" + randomResult1;
		}
		return result;
	}
	
	public String getLost() {
		return lost;
	}
	
	public String getDestroyed() {
		return destroyed;
	}
}
